<?php
// +-------------------------------------------------------------------
// |
// +-------------------------------------------------------------------
// | Copyright (c) 2009-2016 All rights reserved.
// +-------------------------------------------------------------------
namespace Service\Business;

use Kcdns\Admin\Controller\PublicController;
class Collection extends \Service\Common\BaseModel
{
    protected $name = 'business_collection';
    
    public function isBusiness($uid,$value)
    {
    	$save = M('user')->where(['uid'=>$uid])->save(['is_business'=>$value]);
    	if($save === false){
    		throw new \Exception('商家入驻失败');
    	}
    	return true;
    }
    
    public function checkNo($no)
    {
    	$result = $this->where(['no'=>$no])->find();
    	if (!$result) {
    		throw new \Exception('无效的商家编号');
    	}
    	return true;
    }
    
    public function checkData($data,$status = 'add',$id = '')
    {
    	$data = OE('Util')->validate($data, [
    			'business_collection.uid'=>'required;label=用户名',
    			'business_collection.referer_id' => 'required;label=推荐人',
    			'business_collection.sign' => 'required;label=签署协议',
    			'business_collection.type' => 'required;label=入驻类型',
    			'business_collection.company' => 'required;label=公司名称',
    			'business_collection.business_licence' => 'required;label=营业执照',
    			'business_collection.revenue'=>'required;label=税号',
    			'business_collection.location' => 'required;label=地区',
    			'business_collection.address' => 'required;label=详细地址',
    			]);
        if ($data['business_collection.sign'] != 1) {
        	throw new \Exception('请先签署协议');
        }
    	$user = $this->getUserList('b.username',$data['business_collection.uid']);
    	if (!$user) {
    		throw new \Exception('用户名不存在');
    	}
    	$result = $this->getCollectionFind('uid',$user['uid']);
    	if ($status == 'edit') {
    		if ($result['id'] != $id) {
    			throw new \Exception('该用户名已经入驻');
    		}
    	}else {
	    	if ($result) {
	    		throw new \Exception('该用户名已经入驻');
	    	}
    	}
    	$referer = $this->getUserList('b.username',$data['business_collection.referer_id']);
    	if (!$referer || $user['uid'] == $referer['uid']) {
    		throw new \Exception('推荐人错误');
    	}
    	$no = $this->getNo(6);
    	return [$user['uid'],$referer['uid'],$no];
    }
    
    public function getCollectionFind($field,$where)
    {
    	$result = $this->where([$field=>$where])->find();
    	return $result;
    }
   
    
    public function getUserList($field,$where){
    	$result = M('user')->alias('a')
					       ->join('__UCENTER_MEMBER__ b on b.id = a.uid')
					       ->where([$field=>$where])
					       ->find();
    	return $result;
    }
    

    public function getNo($num = 5)
    {
    	while (1) {
    		$str = O('util')->rand($num);
    		$count = $this->where(['no' => $str])->count();
    		if ($count) {
    			continue;
    		}
    		return $str;
    	}
    }
    
}